<template>
  <div style="display: flex; flex-direction: column; height: 100%">
    <SearchList :params="tableParams" :exclude-keys="['status']" @search="search">
      <template #left>
        <StatusTab v-model:active="activeTab" :tabs="statusList" @change="changeTab" />
      </template>
      <SearchItem title="关键字搜索">
        <a-input v-model:value="tableParams.keywords" placeholder="合同相对方/合同标的物" allow-clear />
      </SearchItem>
      <SearchItem title="合同编号">
        <a-input v-model:value="tableParams.contractNo" placeholder="合同编号" allow-clear />
      </SearchItem>
      <SearchItem title="合同相对方">
        <a-input v-model:value="tableParams.counterparty" placeholder="合同相对方" allow-clear />
      </SearchItem>
      <SearchItem title="合同标的物">
        <a-input v-model:value="tableParams.subject" placeholder="合同标的物" allow-clear />
      </SearchItem>
      <SearchItem title="规格">
        <a-input v-model:value="tableParams.specification" placeholder="规格" allow-clear />
      </SearchItem>
      <SearchItem title="合同月份">
        <a-date-picker v-model:value="tableParams.month" placeholder="合同月份" picker="month" />
      </SearchItem>
      <template #actions>
        <a-popover v-model:open="popupVisible" trigger="click" placement="bottom" :arrow="false" class="mr-10px">
          <template #content>
            <div @click="popupVisible = false">
              <p class="pointer" @click="importVisible = true">导入合同台账</p>
              <p class="pointer" @click="exportRef.open('/admin/contract/export', tableParams)">导出excel</p>
            </div>
          </template>
          <div class="pointer choose-btn">
            <span>生成数据</span>
            <icon-font type="icon-yumengtubiao_jiantouxiangxia" style="margin-left: 10px; color: #7d8389" />
          </div>
        </a-popover>
        <a-button v-permissions="['dispatch:contract:add']" size="small" type="primary" @click="formRef.edit(null)">新建</a-button>
      </template>
    </SearchList>
    <BoliTabel ref="tableRef" :columns="columns" api="/admin/contract/list" :params="tableParams">
      <template #status="{ text }">
        <MatchStatus :status="text" />
      </template>
      <template #action="{ record }">
        <Action>
          <div v-permissions="['dispatch:contract:edit']" class="action-item" @click="formRef.edit({ ...record })">编辑</div>
          <div v-permissions="['dispatch:contract:delete']" class="action-item" @click="handleDelete(record)">删除</div>
        </Action>
      </template>
    </BoliTabel>
    <a-modal v-model:open="importVisible" title="导入合同台账" width="520px" :footer="null" destroy-on-close @cancel="closeImport">
      <ImportExcel :excel="excelParam" placeholder="选择合同台账计算月份" :select-month="true" @flush="flushTable" />
    </a-modal>
    <ContractForm ref="formRef" @success="tableRef.refresh()" />
    <ExportExcel ref="exportRef" />
  </div>
</template>

<script setup>
import Action from '@/components/BoliTable/Action.vue'
import BoliTabel from '@/components/BoliTable/index.vue'
import ExportExcel from '@/components/ExportExcel/index.vue'
import ImportExcel from '@/components/ImportExcel/index.vue'
import MatchStatus from '@/components/MatchStatus/index.vue'
import StatusTab from '@/components/StatusTab/index.vue'
import ContractForm from './ContractForm.vue'

import { columns, excelParam, statusData } from './data'

defineOptions({
  name: 'DispatchContract',
})

const tableParams = reactive({
  keywords: null,
  status: null,
})

const activeTab = ref(0)

const statusList = reactive([...statusData])

const importVisible = ref(false)
const popupVisible = ref(false)
const formRef = ref(null)
const tableRef = ref(null)
const exportRef = ref(null)

// 切换tab
function changeTab(item) {
  tableParams.status = item.query
  tableRef.value?.refresh()
}

function getStatusCount() {
  httpRequest('/admin/contract/count', tableParams).then(res => {
    statusList[0].value = res.all
    statusList[1].value = res.pendingMatch
    statusList[2].value = res.matched
  })
}

/**
 * 搜索
 * @param keywords
 */
function search(keywords) {
  if (keywords) {
    tableParams.keywords = keywords
  }
  tableRef.value.refresh()
  getStatusCount()
}

function flushTable(excelUrl) {
  refresh.flush = true
  refresh.failExcel = excelUrl
}
/**
 * 删除合同
 * @param record
 */
function handleDelete(record) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除合同标的物 "${record.subject}-${record.specification}" 吗？`,
    okText: '确定',
    cancelText: '取消',
    okType: 'danger',
    onOk: async () => {
      await httpRequest(`/admin/contract/delete`, { id: record.id })
      message.success('删除成功')
      tableRef.value?.refresh()
    },
  })
}
/**
 * 关闭导入框
 */
function closeImport() {
  if (refresh.failExcel) {
    Modal.confirm({
      title: '失败数据下载提示',
      okText: '下载',
      content: '您有导入失败数据未下载，请点击下载',
      onOk() {
        window.location.href = refresh.failExcel
        return Promise.resolve()
      },
    })
  }
  if (refresh.flush) {
    getStatusCount()
    tableRef.value?.refresh()
  }
  refresh.flush = false
}

getStatusCount()
</script>

<style lang="less" scoped>
.status-list {
  display: flex;
  align-items: center;
  height: 100%;

  & > div {
    margin-right: 20px;
    font-size: 14px;
    color: #111;

    & span {
      margin-right: 5px;
    }
  }
}

.batch-btns {
  margin-right: 10px;

  .choose-btn {
    height: 30px;
    padding: 0 8px;
    font-size: 14px;
    line-height: 30px;
    color: #575757;
    cursor: pointer;
    background: #f2f5f7;
    border-radius: 4px;
  }
}
</style>
